package socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 服务端
 */
public class UDPServer {
    //1. 创建套接字
    //2. 接收数据
    //3. 处理数据
    //4. 显示数据
    public DatagramSocket socket = null;

    //服务端, 需要指定端口号
    public UDPServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务端已启动, 等待接收数据...");
        /**
         * void receive(DatagramPacket p)
         *  DatagramPacket: 数据报
         */
        /**
         * DatagramPacket(byte buf[], int length)
         * 参数说明
         * buf: 接收数据的数组, 类似于食堂打饭的餐盘
         * length: 接收数据的长度
         */
        while (true) {
            byte buf[]  = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf,buf.length);
            socket.receive(packet);
            //处理数据
            String request = new String(packet.getData(),0,packet.getLength(),
                    "UTF-8");

            System.out.printf("接收到客户端的数据:[%s:%d]:%s\n",packet.getAddress().getHostName(),
                    packet.getPort(),request);
        }

    }

    public static void main(String[] args) throws IOException {
        UDPServer server = new UDPServer(9090);
        server.start();
    }

}
